package com.google.code.kkeenn.grid.data;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.rits.cloning.Cloner;

public class Grid {

	public Cell[][] grid;
	private boolean numbersGenerated;
	private Random random;

	public Grid(int size) {
		this.grid = new Cell[size][size];
		this.numbersGenerated = false;
		this.random = new Random(System.currentTimeMillis());
		generateNumbers();
		genrateGroupings();
	}

	private void generateNumbers() {
		int randomIndex = 0;
		List<Integer> stillToUse;
		List<Integer> possibleValues = new ArrayList<Integer>();
		Cloner cloner = new Cloner();

		for (int i = 0; i < this.grid.length; i++)
			possibleValues.add(i + 1);

		for (int i = 0; i < this.grid.length; i++) {
			stillToUse = cloner.deepClone(possibleValues);
			print(this.grid);
			for (int j = 0; j < this.grid.length; j++) {
				randomIndex = this.random.nextInt(stillToUse.size());
				for (int k = 0; k < stillToUse.size(); k++) {
					int value = stillToUse.get((randomIndex + k)
							% stillToUse.size());
					System.out.println("index = "
							+ stillToUse.get((randomIndex + k)
									% stillToUse.size()));
					System.out.println("value = " + value);
					if (isValid(i, j, value)) {
						this.grid[i][j] = new Cell(value);
						stillToUse.remove(Integer.valueOf(value));
						print(this.grid);
						break;
					} else if ((k + 1) >= stillToUse.size()) {
						for (int l = 0; l < this.grid.length; l++) {
							if (isValid(i, l, value)
									&& this.grid[i][l] != null
									&& isValid(i, j, this.grid[i][l].getValue())) {
								int temp = value;
								value = this.grid[i][l].getValue();
								this.grid[i][l].setValue(temp);
								break;
							}
						}
					}
				}
			}
		}
	}

	private boolean isValid(int x, int y, int v) {
		for (int i = 0; i < this.grid.length; i++) {
			if (this.grid[x][i] != null && this.grid[x][i].getValue() == v)
				return false;
			if (this.grid[i][y] != null && this.grid[i][y].getValue() == v)
				return false;
		}
		return true;
	}

	private void genrateGroupings() {
		if (!numbersGenerated) {
			generateNumbers();
		}
		// Generate groupings randomly
	}

	public static void main(String[] args) {
		Grid x = new Grid(5);
		print(x.grid);
	}

	private static void print(Cell[][] grid) {
		for (int i = 0; i < grid.length; i++) {
			for (int j = 0; j < grid.length; j++) {
				if (grid[i][j] == null)
					System.out.print("X ");
				else
					System.out.print(grid[i][j].getValue() + " ");
			}
			System.out.println();
		}
		System.out.println();
	}

}
